package qhdx.fiveGC.controller;

import qhdx.fiveGC.entity.User;
import qhdx.fiveGC.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;

    @RequestMapping("/login")
    public int login(User user, String rem, HttpServletResponse response, HttpSession session){
        User u = mapper.selectByUsername(user.getUsername());
        if (u!=null){
            //判断密码是否一致
            if (u.getPassword().equals(user.getPassword())){
                System.out.println("user = " + user + ", rem = " + rem);
                if (rem!=null){//代表记住用户名和密码
                    //通过Cookie保存用户名和密码
                    Cookie c1 = new Cookie("username",user.getUsername());
                    Cookie c2 = new Cookie("password",user.getPassword());
                    //设置保存时间
                    c1.setMaxAge(60*60*24*30);
                    //把Cookie下发给客户端
                    response.addCookie(c1);
                    response.addCookie(c2);

                }
                //记住登录状态
                session.setAttribute("user",u);

                return 1;//登录成功
            }else{
                return 3;//密码错误
            }
        }
        return 2;//用户名不存在
    }
    @RequestMapping("/checkLogin")
    public User checkLogin(HttpSession session){
        return (User) session.getAttribute("user");
    }

    @RequestMapping("/logout")
    public void logout(HttpSession session){
         session.removeAttribute("user");
    }


}
